package com.qf.commons;

import com.qf.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * JWT签发校验工具，生成和校验
 */
//生成
public class JwtUtil {
    private static String key = "lxkeyword";

    private static int timeout = 1000 * 60 * 60 * 24 * 7;

    public static String createToken(User user,String devId){
        JwtBuilder builder = Jwts.builder()
                .setId(user.getId()+"")
                .setSubject(user.getNickname())
                .setIssuedAt(new Date())
                .claim("id",user.getId())
                .claim("nickname",user.getNickname())
                .setExpiration(new Date(System.currentTimeMillis() + timeout))
                .signWith(SignatureAlgorithm.HS256,key + devId);
        String jwtToken = builder.compact();

        return jwtToken;
    }
    //解析（校验）
    public static User parseToken(String token,String devId){
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(key + devId)
                    .parseClaimsJws(token)
                    .getBody();
            if(claims != null){
                int id = (Integer) claims.get("id");

                String nickname = (String) claims.get("nickname");

                User user = new User()
                        .setId(id)
                        .setNickname(nickname);
                return user;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
